package com.leo.springbootmultithreadbasic.threadcounter.cyclicbarrier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author Leo
 * @version V1.0
 */
public class MainDemo {
    private static Logger logger = LoggerFactory.getLogger(MainDemo.class);

    private static final int THREAD_COUNT_NUM = 5;

    public static void main(String[] args) {
        testCyclicBarrier();
    }


    /**
     * 测试场景：
     * <p>
     * 设置两个屏障点
     */
    private static void testCyclicBarrier() {
        // 设置第一个屏障点
        CyclicBarrier cyclicBarrier = new CyclicBarrier(
                THREAD_COUNT_NUM,
                () -> {
                    logger.info("All threads reach the first barrier point.");
                    buildSecondBarrier();
                }
        );

        for (int i = 0; i <= THREAD_COUNT_NUM; i++) {
            int index = i + 1;
            new Thread(() -> {
                try {
                    logger.info("第 {} 个线程到达Barrier Point", index);
                    cyclicBarrier.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }

    private static void buildSecondBarrier() {
        // 设置第二个屏障点
        CyclicBarrier cyclicBarrier2 = new CyclicBarrier(THREAD_COUNT_NUM, () -> logger.info("All threads reach the second barrier point."));

        for (int i = 1; i <= THREAD_COUNT_NUM; i++) {
            int index = i;
            new Thread(() -> {
                try {
                    logger.info("第 {} 个线程到达Barrier Point2", index);
                    cyclicBarrier2.await();
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
